package com.czz.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czz.manage.entity.Category;
import com.czz.manage.entity.Course;
import com.czz.manage.mapper.CategoryMapper;
import com.czz.manage.mapper.CourseMapper;
import com.czz.manage.service.CategoryService;
import com.czz.manage.utils.ExcelImportUtil;
import com.czz.manage.vo.CategoryNestedVo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName: CategoryServiceImpl
 * @Author Czz
 * @Date 2019/12/29
 * @Time 10:07
 **/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    CourseMapper courseMapper;

    @Override
    public void saveParentCategory(Category category) {
        categoryMapper.insert(category);
        Category temp = new Category();
        temp.setName("默认二级分类").setParentId(category.getId()).setSort("0");
        categoryMapper.insert(temp);
    }

    @Override
    public void saveChildCategory(Category category) {
        categoryMapper.insert(category);
    }

    @Override
    public Category getParentCategoryByName(String name) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_name",name);
        queryWrapper.eq("category_parent_id","0");
        return categoryMapper.selectOne(queryWrapper);
    }

    @Override
    public Category getChildCategoryByName(String name, String parentId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_name",name);
        if (!StringUtils.isEmpty(parentId)){
            queryWrapper.eq("category_parent_id",parentId);
        }
        return categoryMapper.selectOne(queryWrapper);
    }

    @Override
    public void updateCategoryById(Category category) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_name",category.getName());
        Category temp = categoryMapper.selectOne(queryWrapper);

        //存在同名分类，不更新名称
        if (!ObjectUtils.isEmpty(temp)) {
            category.setName(categoryMapper.selectById(category.getId()).getName());
        }
        categoryMapper.updateById(category);
    }

    @Override
    @Transactional
    public Boolean deleteCategoryById(String id) {
        Category category = categoryMapper.selectById(id);


        //如果为一级分类，删除此分类下所有二级分类
        if (category.getParentId().equals("0")){
            //判断此一级分类下是否存在课程
            QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
            courseQueryWrapper.eq("category_parent_id",id);
            Integer count = courseMapper.selectCount(courseQueryWrapper);
            //存在课程
            if (count > 0) return false;

            //不存在课程
            QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("category_parent_id",category.getId());
            List<Category> categoryList = categoryMapper.selectList(queryWrapper);
            ArrayList idList = new ArrayList();
            for (int i=0; i<categoryList.size(); i++){
                Category temp = categoryList.get(i);
                idList.add(temp.getId());
            }
            categoryMapper.deleteBatchIds(idList);
            categoryMapper.deleteById(id);
            return true;
        }
        //如果二级分类所属分类中只剩最后一个，也一同删除一级分类
        else {
            //判断此一级分类下是否存在课程
            QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
            courseQueryWrapper.eq("category_id",id);
            Integer courseCount = courseMapper.selectCount(courseQueryWrapper);
            //存在课程
            if (courseCount > 0) return false;

            //不存在课程
            QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("category_parent_id",category.getParentId());
            Integer count = categoryMapper.selectCount(queryWrapper);
            if (count <= 1){
                categoryMapper.deleteById(category.getParentId());
            }
            categoryMapper.deleteById(category.getId());
            return true;
        }
    }

    @Override
    @Transactional
    public List<String> batchImportCategory(MultipartFile file) throws Exception {
        //错误消息列表
        List<String> errorMsg = new ArrayList<>();

        //创建工具类对象
        ExcelImportUtil excelHSSFUtil = new ExcelImportUtil(file.getInputStream());
        //获取工作表
        Sheet sheet = excelHSSFUtil.getSheet();

        int rowCount = sheet.getPhysicalNumberOfRows();
        if (rowCount <= 1) {
            errorMsg.add("请填写数据");
            return errorMsg;
        }

        for (int rowNum = 1; rowNum < rowCount; rowNum++) {

            Row rowData = sheet.getRow(rowNum);
            // 行不为空
            if (rowData != null) {

                //获取一级分类
                String levelOneValue = "";
                Cell levelOneCell = rowData.getCell(0);
                if(levelOneCell != null){
                    levelOneValue = excelHSSFUtil.getCellValue(levelOneCell).trim();
                    if (StringUtils.isEmpty(levelOneValue)) {
                        errorMsg.add("第" + rowNum + "行一级分类为空");
                        continue;
                    }
                }

                //判断一级分类是否重复
                Category category = this.getParentCategoryByName(levelOneValue);
                String parentId = null;
                if (ObjectUtils.isEmpty(category)){
                    //将一级分类存入数据库
                    Category categoryLevelOne = new Category();
                    categoryLevelOne.setName(levelOneValue);
                    categoryLevelOne.setSort(String.valueOf(rowNum));
                    categoryMapper.insert(categoryLevelOne);
                    parentId = categoryLevelOne.getId();
                }
                else parentId = category.getId();

                //获取二级分类
                String levelTwoValue = "";
                Cell levelTwoCell = rowData.getCell(1);
                if(levelTwoCell != null){
                    levelTwoValue = excelHSSFUtil.getCellValue(levelTwoCell).trim();
                    if (StringUtils.isEmpty(levelTwoValue)) {
                        errorMsg.add("第" + rowNum + "行二级分类为空");
                        continue;
                    }
                }
                //判断二级分类是否重复
                Category categoryChild = this.getChildCategoryByName(levelTwoValue, parentId);
                Category categoryLevelTwo = null;
                if (ObjectUtils.isEmpty(categoryChild)){
                    //将二级分类存入数据库
                    categoryLevelTwo = new Category();
                    categoryLevelTwo.setName(levelTwoValue);
                    categoryLevelTwo.setParentId(parentId);
                    categoryLevelTwo.setSort(String.valueOf(rowNum));
                    categoryMapper.insert(categoryLevelTwo);
                }
            }
        }

        return errorMsg;
    }

    @Override
    public List<CategoryNestedVo> getCategoryNestedList() {
        return categoryMapper.getCategoryNestedList("0");
    }

    @Override
    public List<CategoryNestedVo> getCategoryPageList(Page<CategoryNestedVo> pageParam,Category category) {
        return categoryMapper.getCategoryPageList(pageParam,category);
    }
}
